package com.woniuxy.config;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.woniuxy.entity.ShopOrder;
import com.woniuxy.enums.order.ShopOrderStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.alipay.api.AlipayClient;


import java.math.BigDecimal;
import java.util.Date;

@Component
public class PayUtil {
    //以下公私钥在https://open.alipay.com/develop/sandbox/app里面获取
    //appid
    @Value("${alipay.appId}")
    private String APP_ID;
    //应用私钥
    @Value("${alipay.merchantPrivateKey}")
    private  String APP_PRIVATE_KEY;
    //编码器
    @Value("${alipay.charset}")
    private  String CHARSET;
    // 支付宝公钥
    @Value("${alipay.alipayPublicKey}")
    private  String ALIPAY_PUBLIC_KEY;
    //网关，这是沙箱接口路径,正式路径https://openapi.alipay.com/gateway.do
    @Value("${alipay.gatewayUrl}")
    private  String GATEWAY_URL;
    private final String FORMAT = "JSON";
    //签名方式
    @Value("${alipay.signType}")
    private  String SIGN_TYPE;
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    @Value("${alipay.notifyUrl}")
    private  String NOTIFY_URL;
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    @Value("${alipay.returnUrl}")
    private  String RETURN_URL ;
    private AlipayClient alipayClient = null;

    //支付宝官方提供的接口
    public String sendRequestToAlipay(String outTradeNo, BigDecimal totalAmount, String subject, String type) throws AlipayApiException {
        //获得初始化的AlipayClient
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);
/**
 * pc端用于页面跳转
 */
        //商品描述（可空）
       if(type.equals("pc")){
           String body = "";
           alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\"," // 修正参数名
                   + "\"total_amount\":\"" + totalAmount + "\","
                   + "\"subject\":\"" + subject + "\","
                   + "\"body\":\"" + body + "\","
                   + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
           //pc跳转请求
           String result = alipayClient.pageExecute(alipayRequest).getBody();
           System.out.println("返回的结果是："+result );
           return result;
       } else if(type.equals("mini")){
           // 1. 创建扫码支付请求对象
           AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
           request.setNotifyUrl(NOTIFY_URL);

// 2. 设置业务参数
           request.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                   + "\"total_amount\":\"" + totalAmount + "\","
                   + "\"subject\":\"" + subject + "\","
                   + "\"store_id\":\"test_store_id\"}");

// 3. 执行请求
           AlipayTradePrecreateResponse response = alipayClient.execute(request);

// 4. 获取二维码内容
           if (response.isSuccess()) {
               String qrCode = response.getQrCode();
               System.out.println("返回的二维码内容是：" + qrCode);
               JSONObject result = new JSONObject();
               result.put("qrCode", qrCode);
               result.put("outTradeNo", outTradeNo);
               return result.toString();
           } else {
               throw new RuntimeException("生成二维码失败: " + response.getSubMsg());
           }
       }
       return "类型错误";
    }
    //    通过订单编号查询
    public AlipayTradeQueryResponse query(String id) {
        if (alipayClient == null) {
            alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        }
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        request.setBizContent(bizContent.toString());

        try {
            return alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            // 这里可以抛出自定义异常或返回null，根据你的异常处理策略
            return null;
        }
    }
}
